package com.quan.system.service.impl;

import java.io.Serializable;
import java.time.LocalDate;
import java.time.format.DateTimeFormatter;
import java.util.ArrayList;
import java.util.Collection;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import com.alibaba.fastjson.JSON;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.quan.common.bean.PageBean;
import com.quan.common.core.MyBaseServiceImpl;
import com.quan.common.enums.DateStyle;
import com.quan.common.utils.CronDateUtils;
import com.quan.common.utils.DateUtils;
import com.quan.common.utils.IdCardUtils;
import com.quan.common.utils.MathUtil;
import com.quan.common.utils.Pinyin4jHelper;
import com.quan.system.common.dto.employee.EmpCountByAreaDTO;
import com.quan.system.common.dto.employee.EmpCountTotalDTO;
import com.quan.system.common.dto.employee.YearHolidayDTO;
import com.quan.system.common.dto.excel.SystemEmployeeImportExcel;
import com.quan.system.entity.SystemCompany;
import com.quan.system.entity.SystemDepartment;
import com.quan.system.entity.SystemEmployee;
import com.quan.system.entity.SystemJob;
import com.quan.system.entity.SystemPost;
import com.quan.system.entity.SystemSettings;
import com.quan.system.entity.SystemUser;
import com.quan.system.mapper.SystemEmployeeMapper;
import com.quan.system.service.SystemCompanyService;
import com.quan.system.service.SystemDepartmentService;
import com.quan.system.service.SystemEmployeeDeptHistoryService;
import com.quan.system.service.SystemEmployeeDimissionRemarkService;
import com.quan.system.service.SystemEmployeeJoinDimissionService;
import com.quan.system.service.SystemEmployeeLabourContractHistoryService;
import com.quan.system.service.SystemEmployeePostHistoryService;
import com.quan.system.service.SystemEmployeeService;
import com.quan.system.service.SystemJobService;
import com.quan.system.service.SystemPostService;
import com.quan.system.service.SystemSettingsService;
import com.quan.system.service.SystemUserService;

import cn.hutool.core.bean.BeanUtil;
import lombok.extern.slf4j.Slf4j;

/**
 * <p>
 * 员工表 服务实现类
 * </p>
 *
 * @author 杨浩泉
 * @since 2019-06-24
 */
@Slf4j
@Service
public class SystemEmployeeServiceImpl extends MyBaseServiceImpl<SystemEmployeeMapper, SystemEmployee> implements SystemEmployeeService {

	@Autowired
	private SystemEmployeeMapper mapper;

	@Autowired
	private SystemCompanyService companyService;

	@Autowired
	private SystemDepartmentService departmentService;

	@Autowired
	private SystemPostService postService;

	@Autowired
	private SystemUserService userService;

	@Autowired
	private SystemEmployeeDeptHistoryService employeeDeptHistoryService;

	@Autowired
	private SystemEmployeeDimissionRemarkService employeeDimissionRemarkService;

	@Autowired
	private SystemEmployeeJoinDimissionService employeeJoinDimissionService;

	@Autowired
	private SystemEmployeeLabourContractHistoryService employeeLabourContractHistoryService;

	@Autowired
	private SystemEmployeePostHistoryService employeePostHistoryService;

	@Autowired
	private SystemJobService jobService;
	
	@Autowired 
    private SystemSettingsService settingsService;

	@Override
	public boolean save(SystemEmployee entity) {

		if (StringUtils.isNotBlank(entity.getIdNum())) { // 根据身份证解析（省份，出生日期，男女）
			entity.setRoot(IdCardUtils.getProvinceByIdCard(entity.getIdNum()));
			entity.setBirthDay(DateUtils.format(DateUtils.parse(IdCardUtils.getBirthByIdCard(entity.getIdNum()), DateStyle.YYYYMMDD), DateStyle.YYYY_MM_DD));
			entity.setGender(IdCardUtils.getGenderByIdCard(entity.getIdNum()));
		}

		boolean flag = super.save(entity);

		if (flag) {
			if (null != entity.getTermiDate()) { // 设置员工劳动合同到期提醒定时器
				this.setNotifyByHTDQ(entity);
			}
			if (null != entity.getEntryDate()) { // 设置员工年假到期提醒定时器
				this.setNotifyYearHoliday(entity);
			}
			if (null != entity.getPromotion()) { // 设置员工转正提醒定时器
				//转正日期
				Date zzDate = DateUtils.LocalDateToUdate(entity.getPromotion());
				//当前日期
				Date curDate = DateUtils.parse(DateUtils.getDate(), DateStyle.YYYY_MM_DD);
				
				long zzMillis = DateUtils.getMillis(zzDate);
				long curMillis = DateUtils.getMillis(curDate);
				
				if(zzMillis > curMillis) { // 转正日期大于当前日期才设定定时器
					this.setNotifyZhuanZheng(entity);
				}
			}
		}

		return flag;
	}

	@Override
	public boolean updateById(SystemEmployee entity) {
		boolean flag = super.updateById(entity);
		if (flag) {
			if (entity.getWorkingStatus().equals("离职") && entity.getIsSchedulerHtdt() == 1) { // 员工状态为离职时，删除劳动合同到期定时器
				// 删除员工年假提醒定时器
				this.jobService.deleteJobByName("员工劳动合同到期提醒【" + entity.getNum() + "-" + entity.getName() + "】");
				// 删除员工年假提醒定时器
				this.jobService.deleteJobByName("员工年假到期提醒【" + entity.getNum() + "-" + entity.getName() + "】");
			} else {
				if (null != entity.getTermiDate()) { // 设置员工劳动合同到期提醒定时器
					this.setNotifyByHTDQ(entity);
				}
				if (null != entity.getEntryDate()) { // 设置员工年假到期提醒定时器
					this.setNotifyYearHoliday(entity);
				}
			}
		}
		return flag;
	}

	@Override
	public IPage<SystemEmployee> selectEmployeePage(SystemEmployee entity, PageBean pageBean) {
		Page<SystemEmployee> page = new Page<>(pageBean.getPage(), pageBean.getLimit());
		
		if(StringUtils.isNotBlank(pageBean.getSortOrder()) && StringUtils.isNotBlank(pageBean.getSortName())) {
			if(pageBean.getSortOrder().equalsIgnoreCase("DESC")) {
				page.setDesc(pageBean.getSortName()); 
			} else if(pageBean.getSortOrder().equalsIgnoreCase("ASC")) {
				page.setAsc(pageBean.getSortName());
			}
		}
		return this.mapper.selectEmployeePage(page, entity);
	}

	@Override
	public boolean removeByIds(Collection<? extends Serializable> idList) {
		boolean falg = super.removeByIds(idList);

		idList.forEach(id -> {
			this.employeeDeptHistoryService.deleteByEmpId(id);
			this.employeeDimissionRemarkService.deleteByEmpId(id);
			this.employeeJoinDimissionService.deleteByEmpId(id);
			this.employeeLabourContractHistoryService.deleteByEmpId(id);
			this.employeePostHistoryService.deleteByEmpId(id);
		});

		return falg;
	}

	@Override
	public Integer importEmpInfoData(List<SystemEmployeeImportExcel> emps, boolean isAccount) {
		int count = 0;

		for (SystemEmployeeImportExcel emp : emps) {
			if (null != emp.getNum()) {
				boolean hasExist = super.hasExist("num", emp.getNum(), SystemEmployee.class);

				if (!hasExist) {
					SystemEmployee entity = new SystemEmployee();
					BeanUtil.copyProperties(emp, entity);

					if (StringUtils.isBlank(emp.getEmail())) { // 将姓名转换成汉子拼音
						entity.setEmail(Pinyin4jHelper.getPinYin(emp.getName()) + "@whizen.com");
					}

					if (StringUtils.isNotBlank(emp.getIdNum())) { // 根据身份证解析（省份，出生日期，男女）
						entity.setRoot(IdCardUtils.getProvinceByIdCard(emp.getIdNum()));
						entity.setBirthDay(DateUtils.format(DateUtils.parse(IdCardUtils.getBirthByIdCard(emp.getIdNum()), DateStyle.YYYYMMDD), DateStyle.YYYY_MM_DD));
						entity.setGender(IdCardUtils.getGenderByIdCard(emp.getIdNum()));
					}

					if (StringUtils.isBlank(emp.getWorkingStatus())) { // 将姓名转换成汉子拼音
						entity.setWorkingStatus("在职");
					}

					if (null != emp.getTermiDate()) {
						if (emp.getTermiDate().trim().equals("无固定期")) {
							entity.setTermiDate(null);
							entity.setIsLimit(2);
						} else { // 有期限
							entity.setIsLimit(1);
						}
					} else { // 未签合同
						entity.setIsLimit(3);
					}

					try {
						// 计算社龄：获取（入职日期-当前日期）两个日期相差天数 / 365
						double distanceOfTwoDate = DateUtils.getDistanceOfTwoDate(DateUtils.parse(emp.getEntryDate(), DateStyle.YYYY_MM_DD), new Date());
						String sl = MathUtil.format((distanceOfTwoDate / 365), "#.#");
						entity.setEmpTime(sl);
					} catch (Exception e) {
						log.error("入职日期格式不正确，无法录入，姓名：{}, 入职日期：{}", emp.getName(), emp.getEntryDate());
					}

					if (StringUtils.isNotBlank(emp.getCompany())) { // 员工关联公司
						entity.setCompanyId(this.relatedCompany(emp.getCompany()));
					}
					if (StringUtils.isNotBlank(emp.getDept())) { // 员工关联部门
						entity.setDepartmentId(this.relatedDepartment(emp.getDept()));
					}
					if (StringUtils.isNotBlank(emp.getPost())) { // 员工关联岗位
						entity.setPostId(this.relatedPost(emp.getPost()));
					}

					entity.setIsAccount(isAccount ? 1 : 0); // 是否生成登录账号

					// 保存员工对象
					boolean flag = super.save(entity);

					if (flag) { // 同时创建登录账号
						this.generateAccount(entity, isAccount);
					}

					if (StringUtils.isNotBlank(emp.getTermiDate())) { // 设置合同到期提醒定时器
						this.setNotifyByHTDQ(entity);
					}

					if (StringUtils.isNotBlank(emp.getEntryDate())) { // 设置年假提醒定时器
						this.setNotifyYearHoliday(entity);
					}
					
					if (StringUtils.isNotBlank(emp.getPromotion())) { // 设置员工转正提醒定时器
						//转正日期
						Date zzDate = DateUtils.parse(emp.getPromotion(), DateStyle.YYYY_MM_DD);
						//当前日期
						Date curDate = DateUtils.parse(DateUtils.getDate(), DateStyle.YYYY_MM_DD);
						
						long zzMillis = DateUtils.getMillis(zzDate);
						long curMillis = DateUtils.getMillis(curDate);
						
						if(zzMillis > curMillis) { // 转正日期大于当前日期才设定定时器
							this.setNotifyZhuanZheng(entity);
						}
					}

					count++;
				}
			} else {
				continue;
			}
		}

		return count;
	}

	/**
	 * 设置年假到期定时器 根据入职日期月份来设定每年提醒
	 * 
	 * @param emp
	 */
	private void setNotifyYearHoliday(SystemEmployee emp) {
		if (null != emp && null != emp.getEntryDate() && emp.getWorkingStatus().equals("在职")) { // 员工入职日期不能为空
			
			// 员工入职日期减10天（提前十天邮件提醒）
			LocalDate date = emp.getEntryDate().minusDays(10);
			// 定时触发表达式：每年的某月某日
			String cron = "30 59 11 " + date.getDayOfMonth() + " " + date.getMonthValue() + " ? *";
			
			this.schedulerByYearHoliday(emp, cron);
		}
	}
	
	/**
	 * 设置员工转正定时器
	 * @param emp
	 */
	private void setNotifyZhuanZheng(SystemEmployee emp) {
		if (emp.getWorkingStatus().equals("在职")) {

			// 当前日期
			Date current = new Date();
						
			// 员工转正日期减15天（提前15天邮件提醒）
			LocalDate date = emp.getPromotion().minusDays(15);
			Date minusDate = DateUtils.LocalDateToUdate(date);
			Date originDate = DateUtils.LocalDateToUdate(emp.getPromotion());
			
			int betweenTwoDates = DateUtils.betweenTwoDates(originDate, current);
			
			if(betweenTwoDates > 15) { // 如果转正日期与当前日期相差天数大于15天，则设定定时器提前15天
				
				String jobDate = DateUtils.format(minusDate, DateStyle.YYYY_MM_DD) + " 11:59:30";
				String cron = CronDateUtils.getCron(jobDate); // 将日期转换为cron
				
				this.schedulerByZhuanZheng(emp, cron);
				
			} else if(betweenTwoDates < 15 && betweenTwoDates > 0) { // 如果转正日期与当前日期相差天数小于15并且大于1，则设定定时器的值为相差的天数
				
				LocalDate miniDate = emp.getEntryDate().minusDays(betweenTwoDates);
				String jobDate = DateUtils.format(DateUtils.LocalDateToUdate(miniDate), DateStyle.YYYY_MM_DD) + " 11:59:30";
				String cron = CronDateUtils.getCron(jobDate); // 将日期转换为cron
				
				this.schedulerByZhuanZheng(emp, cron);
			}

		}
	}

	/**
	 * 设置年假定时器
	 * 
	 * @param emp
	 * @param jobCron
	 */
	private void schedulerByYearHoliday(SystemEmployee emp, String jobCron) {
		LocalDate date = emp.getEntryDate().minusDays(10);
		String cronDate = "每年 " + date.getMonthValue() + " " + date.getDayOfMonth() + " 11:01:01";
		
		SystemJob job = new SystemJob();
		job.setJobName("员工年假到期提醒【" + emp.getNum() + "-" + emp.getName() + "】");
		job.setJobDesc("员工年假到期：" + emp.getEntryDate() + "，定时触发日期：" + cronDate);
		job.setJobCron(jobCron);
		job.setJobClassPath("com.quan.system.common.job.YearHolidayJob");
		
		Map<String, Object> jobDataMap = new HashMap<String, Object>();
		jobDataMap.put("empId", emp.getId());
		job.setJobDataMap(jobDataMap);
		job.setJobParams(JSON.toJSONString(jobDataMap));
		
		this.jobService.startJob(job);
		
		emp.setIsSchedulerHoliday(1); // 将该员工年假标识为已设定时器
		super.updateById(emp);
	}
	
	/**
	 * 设置转正定时器
	 * @param emp
	 * @param jobCron
	 */
	private void schedulerByZhuanZheng(SystemEmployee emp, String jobCron) {

		SystemJob job = new SystemJob();
		job.setJobName("员工转正提醒【" + emp.getNum() + "-" + emp.getName() + "】");
		job.setJobDesc("员工转正到期：" + emp.getPromotion() + "，定时触发日期：" + jobCron);
		job.setJobCron(jobCron);
		job.setJobClassPath("com.quan.system.common.job.ZhuanZhengJob");

		Map<String, Object> jobDataMap = new HashMap<String, Object>();
		jobDataMap.put("empId", emp.getId());
		job.setJobDataMap(jobDataMap);
		job.setJobParams(JSON.toJSONString(jobDataMap));

		this.jobService.startJob(job);

		emp.setIsSchedulerZhuanzheng(1); // 将该员工转正标识为已设定时器
		super.updateById(emp);
	}

	/**
	 * 设置合同到期提醒定时器
	 * 
	 * @param date
	 */
	private void setNotifyByHTDQ(SystemEmployee emp) {

		if (null != emp && null != emp.getTermiDate() && emp.getWorkingStatus().equals("在职")) { // 员工劳动合同到期时间不能为空

			// 合同日期
			Date termiDate = DateUtils.LocalDateToUdate(emp.getTermiDate());
			String termiDateStr = DateUtils.format(termiDate, DateStyle.YYYY_MM_DD);
			// 当前日期
			Date current = new Date();

			// 合同日期大于当前日期
			if (DateUtils.getMillis(termiDate) > DateUtils.getMillis(current)) {
				// 取得合同日期减当前日期得相差的天数(合同日期 - 当前日期) = 相差天数
				int betweenTwoDates = DateUtils.betweenTwoDates(termiDate, current);

				// 提前30天设置合同定期提醒
				if (betweenTwoDates >= 30) {
					// 将合同日期减去30天，得到需要定时的日期
					String cron = ConverterDateToCron(termiDate, -30);

					// 设置定时器
					this.schedulerByHTDQ(emp, cron);

					log.debug("==>合同到期相差天数：{}，提前30天设置员工劳动合同到期提醒，合同日期：{}，定时触发提醒日期：{}，Cron表达式：{}", betweenTwoDates, termiDateStr, ConverterCronToDate(cron), cron);
				} else { // 合同日期减当前日期相差的天数小于30天

					if (betweenTwoDates >= 2) { // 相差天数大于两天则将提前提醒天数变为相差天数
						// 将合同日期减去相差天，得到需要定时的日期
						String cron = ConverterDateToCron(termiDate, -betweenTwoDates);

						// 设置定时器
						this.schedulerByHTDQ(emp, cron);

						log.debug("==>合同到期相差天数：{}，提前{}天设置员工劳动合同到期提醒，合同日期：{}，定时触发提醒日期：{}，Cron表达式：{}", betweenTwoDates, betweenTwoDates, termiDateStr, ConverterCronToDate(cron), cron);
					} else if (betweenTwoDates == 1) { // 相差天数等于1，提醒日期这按合同日期来设置
						// 按合同日期来设置定时日期（合同到期当天的11:29:30）
						String cron = ConverterDateToCron(termiDate, 0);

						// 设置定时器
						this.schedulerByHTDQ(emp, cron);

						log.debug("==>合同到期相差天数：{}，设置员工劳动合同到期提醒时间为合同日期当天提醒，合同日期：{}，定时触发提醒日期：{}，Cron表达式：{}", betweenTwoDates, termiDateStr, ConverterCronToDate(cron), cron);
					} else if (betweenTwoDates == 0) {
						// 相差天数等于0，则加一天，定时时间为合同日期的次日
						String cron = ConverterDateToCron(termiDate, 1);

						// 设置定时器
						this.schedulerByHTDQ(emp, cron);

						log.debug("==>合同到期相差天数：{}，设置员工劳动合同到期提醒为合同日期的次日提醒，合同日期：{}，定时触发提醒日期：{}，Cron表达式：{}", betweenTwoDates, termiDateStr, ConverterCronToDate(cron), cron);
					}

				}
				emp.setIsSchedulerHtdt(1); // 将该员工劳动合同标识为已设定时器
				super.updateById(emp);

			} else {
				log.debug("合同到期日期小于等于当前日期...");
			}

		}
	}

	/**
	 * 设置定时
	 * 
	 * @param jobName
	 * @param jobDesc
	 * @param jobCron
	 */
	private void schedulerByHTDQ(SystemEmployee emp, String jobCron) {
		SystemJob job = new SystemJob();
		job.setJobName("员工劳动合同到期提醒【" + emp.getNum() + "-" + emp.getName() + "】");
		job.setJobDesc("员工劳动合同到期时间：" + DateUtils.format(DateUtils.LocalDateToUdate(emp.getTermiDate()), DateStyle.YYYY_MM_DD) + "，合同触发时间：" + ConverterCronToDate(jobCron));
		job.setJobCron(jobCron);
		job.setJobTriggerDate(DateUtils.UDateToLocalDateTime(CronDateUtils.getDate(jobCron)));
		job.setJobClassPath("com.quan.system.common.job.HTDQJob");

		Map<String, Object> jobDataMap = new HashMap<String, Object>();
		jobDataMap.put("empId", emp.getId());
		job.setJobDataMap(jobDataMap);
		job.setJobParams(JSON.toJSONString(jobDataMap));

		this.jobService.startJob(job);
	}

	/**
	 * 将合同日期转换为Cron表达式
	 * 
	 * @param termiDate       合同日期
	 * @param betweenTwoDates 当前日期与合同日期的相差天数
	 * @return
	 */
	private String ConverterDateToCron(Date termiDate, int betweenTwoDates) {
		// 将合同日期减去相差天，得到需要定时的日期
		Date date = DateUtils.addDay(termiDate, betweenTwoDates);
		String jobDate = DateUtils.format(date, DateStyle.YYYY_MM_DD) + " 11:59:30";
		// 将日期转换为cron
		return CronDateUtils.getCron(jobDate);
	}

	/**
	 * 将Cron表达式转换为Date字符串
	 * 
	 * @param cron
	 * @return
	 */
	private String ConverterCronToDate(String cron) {
		return DateUtils.format(CronDateUtils.getDate(cron), DateStyle.YYYY_MM_DD_HH_MM_SS);
	}

	/**
	 * 根据名称返回公司ID
	 * 
	 * @param companyName
	 */
	private Long relatedCompany(String companyName) {
		QueryWrapper<SystemCompany> queryWrapper = new QueryWrapper<SystemCompany>();
		queryWrapper.eq("name", companyName).select("id");
		SystemCompany company = this.companyService.getOne(queryWrapper);
		if (null != company) {
			return company.getId();
		} else {
			return null;
		}
	}

	/**
	 * 根据名称返回部门ID
	 * 
	 * @param departmentName
	 */
	private Long relatedDepartment(String departmentName) {
		QueryWrapper<SystemDepartment> queryWrapper = new QueryWrapper<SystemDepartment>();
		queryWrapper.eq("name", departmentName).select("id");
		SystemDepartment department = this.departmentService.getOne(queryWrapper);
		if (null != department) {
			return department.getId();
		} else {
			return null;
		}
	}

	/**
	 * 根据名称返回岗位ID
	 * 
	 * @param postName
	 */
	private Long relatedPost(String postName) {
		QueryWrapper<SystemPost> queryWrapper = new QueryWrapper<SystemPost>();
		queryWrapper.eq("name", postName).select("id");
		SystemPost post = this.postService.getOne(queryWrapper);
		if (null != post) {
			return post.getId();
		} else {
			return null;
		}
	}

	/**
	 * 生成登录账号
	 * 
	 * @param entity 用户实体
	 * @param isAccount 账号是否为锁定状态
	 */
	private void generateAccount(SystemEmployee entity, boolean isAccount) {
		if (!this.userService.hasExist("username", entity.getNum(), SystemUser.class)) {
			SystemUser user = new SystemUser();
			user.setRealname(entity.getName());
			user.setUsername(entity.getNum());
			user.setEmail(entity.getEmail());
			user.setMobile(entity.getMobile());
			user.setSex(entity.getGender());
			user.setSuperAdmin(false);
			user.setStatus(isAccount);

			this.userService.save(user);
		}

	}

	@Override
	public List<EmpCountByAreaDTO> reportEmpCountByArea() {
		return this.mapper.reportEmpCountByArea();
	}

	@Override
	public List<EmpCountTotalDTO> reportEmpCountByGender() {
		return this.mapper.reportEmpCountByGender();
	}

	@Override
	public List<EmpCountTotalDTO> reportEmpCountByHktype() {
		return this.mapper.reportEmpCountByHktype();
	}

	@Override
	public List<EmpCountTotalDTO> reportEmpCountByWorkingStatus() {
		return this.mapper.reportEmpCountByWorkingStatus();
	}

	@Override
	public List<EmpCountTotalDTO> reportEmpCountByJapLevel() {
		return this.mapper.reportEmpCountByJapLevel();
	}

	@Override
	public List<EmpCountTotalDTO> reportEmpCountByMarital() {
		return this.mapper.reportEmpCountByMarital();
	}

	@Override
	public List<EmpCountTotalDTO> reportEmpCountByEdu() {
		return this.mapper.reportEmpCountByEdu();
	}

	@Override
	public List<EmpCountTotalDTO> reportEmpCountByGraduDate() {
		return this.mapper.reportEmpCountByGraduDate();
	}

	@Override
	public List<EmpCountTotalDTO> reportEmpCountByPost() {
		return this.mapper.reportEmpCountByPost();
	}

	@Override
	public List<SystemEmployee> selectHTJJDQ() {
		// 当前日期
		LocalDate start = LocalDate.now();
		// 当前日期+30天后的日期
		LocalDate end = start.plusDays(30);

		/**
		 * 即将劳动合同到期的员工列表 根据当前即将到期员工的（合同到期日）和（合同到期日+30）来查询出即将到期员工 当前日期 >= and 当前日期+30
		 */
		QueryWrapper<SystemEmployee> queryWrapper = new QueryWrapper<SystemEmployee>();
		queryWrapper.apply("date_format(termi_date, '%Y-%m-%d') >= {0} and date_format(termi_date, '%Y-%m-%d') <= {1}", start, end);
		return super.list(queryWrapper);
	}

	@Override
	public List<SystemEmployee> selectNJJJDQ() {
		DateTimeFormatter formatters = DateTimeFormatter.ofPattern("MM-dd");
		
		// 当前日期
		LocalDate start = LocalDate.now();
		// 当前日期+30天后的日期
		LocalDate end = start.plusDays(30);
		
	    String text1 = start.format(formatters);
	    String text2 = end.format(formatters);

		QueryWrapper<SystemEmployee> queryWrapper = new QueryWrapper<SystemEmployee>();
		queryWrapper.apply("date_format(entry_date, '%m-%d') >= {0} and date_format(entry_date, '%m-%d') <= {1} and date_format(entry_date, '%Y') <> {2}", text1, text2, LocalDate.now().getYear());
		return super.list(queryWrapper);
	}

	
	@Override
	public List<YearHolidayDTO> yearHolidayList(YearHolidayDTO dto) {
		//获取系统设置的默认年假
		SystemSettings settings = this.settingsService.loadSettings();
				
		List<YearHolidayDTO> holidayList = new ArrayList<YearHolidayDTO>() ;
		
		List<YearHolidayDTO> list = this.mapper.selectYearHolidayList(dto);
		list.forEach(item -> {
			YearHolidayDTO holiday = new YearHolidayDTO() ;
			BeanUtil.copyProperties(item, holiday);
			
			holiday.setBetween(DateUtils.getYear() + "-" + (Integer.parseInt(DateUtils.getYear()) + 1));
			
			//计算年假
			Integer emptime = (int)Float.parseFloat(item.getEmpTime()) ;
			holiday.setDay(emptime+(Integer.parseInt(settings.getBackup1())-1));
			
			//该员工如果是之前在公司任职，但离职后，又重新入职公司，需要加上之前在公司任职的社龄来计算年假
			if(null != item.getOldTime()) {
				Integer oldtime = (int)Float.parseFloat(item.getOldTime()) ;
				holiday.setDay(holiday.getDay() + oldtime);
			}
			
			// 年假最多为20天
			if(holiday.getDay() > 20) {
				holiday.setDay(20);
			}
			
			holidayList.add(holiday);
		});
		
		return holidayList;
	}

}
